<?php

namespace app\api\controller\system;

use app\api\controller\Api;
use app\common\config\logic\CommonPickerLogic;
use app\common\config\model\ConfigCompany;
use app\common\config\model\ConfigDictionary;
use app\common\config\model\ConfigSource;
use app\common\config\model\ConfigStatus;
use app\common\config\model\ConfigStore;
use app\common\config\validate\ConfigDictionaryValidate;
use app\common\product\model\StoreCategory;
use app\common\product\model\StoreSupplier;
use app\common\system\logic\FormLogic;
use app\common\system\model\AuthRole;
use app\common\system\model\User;
use think\db\exception\DbException;

class Dictionary extends Api
{
    // 系统初始化picker
    public function initPicker()
    {
        $types = [
            'company' => [
                'class' => new ConfigCompany(),
                'fields' => ['id', 'title', 'short_name']
            ],
            'store' => [
                'class' => new ConfigStore(),
                'fields' => ['id', 'title']
            ],
            'category' => [
                'class' => new StoreCategory(),
                'fields' => ['id', 'title', 'is_member_category', 'customer_model', 'order_model', 'is_four', 'on_member_company'],
                'where' => ['is_sale' => '1']
            ],
            'supplier' => [
                'class' => new StoreSupplier(),
                'fields' => ['id', 'title'],
            ],
            'source' => [
                'class' => new ConfigSource(),
                'fields' => ['id', 'title']
            ],
            'visitStatus' => [
                'class' => new ConfigStatus(),
                'fields' => ['id', 'title', 'is_batch', 'need_next_visit', 'fast']
            ],
        ];

        $result = [];
        foreach ($types as $type => $row) {
            $model = $row['class'];
            if (isset($row['where'])) {
                $result[$type] = $model->where($row['where'])->field($row['fields'])->order('sort,id')->select();
            } else {
                $result[$type] = $model->field($row['fields'])->order('sort,id')->select();
            }

        }

        $model = new ConfigDictionary();
        $rows = $model->select();
        foreach ($rows as $row) {
            $tag = $row->field;
            $result[$tag] = $row->value;
        }

        return success($result);
    }

    public function picker()
    {
        $post = $this->request->post();

        $types = [
            'company' => [
                'class' => new ConfigCompany(),
                'fields' => ['id', 'title', 'short_name']
            ],
            'store' => [
                'class' => new ConfigStore(),
                'fields' => ['id', 'title']
            ],
            'category' => [
                'class' => new StoreCategory(),
                'fields' => ['id', 'title', 'is_member_category', 'customer_model', 'order_model', 'on_member_company', 'is_four'],
                'where' => ['is_sale' => '1']
            ],
            'supplier' => [
                'class' => new StoreSupplier(),
                'fields' => ['id', 'title'],
            ],
            'source' => [
                'class' => new ConfigSource(),
                'fields' => ['id', 'title']
            ],
            'role' => [
                'class' => new AuthRole(),
                'fields' => ['id', 'title']
            ],
            'visitStatus' => [
                'class' => new ConfigStatus(),
                'fields' => ['id', 'title', 'is_batch', 'need_next_visit', 'fast']
            ],
        ];

        $tags = [
            'cooperation',
            'banquetType',
            'paidWay',
            'paidType',
            'timing',
            'invalid'
        ];

        $list = [];
        $type = $post['type'];

        // 大类
        if (isset($types[$type])) {
            $model = $types[$type]['class'];
            $fields = $types[$type]['fields'];

            if (!empty($post['filter'])) {
                $list = $model->where($post['filter'])->order('sort,id')->field($fields)->select();
            } else {
                $list = $model->order('sort,id')->field($fields)->select();
            }
        }

        // 配置
        if (in_array($post['type'], $tags)) {
            $commonLogic = new CommonPickerLogic();
            $list = $commonLogic->getPicker($post['type']);
        }

        if ($post['type'] == 'user') {
            $model = new User();
            $list = $model->where('status', 1)->field('id,realname as title,avatar')->select();
        }

        $result['list'] = $list;
        return success($result);
    }


    public function index()
    {
        $model = new ConfigDictionary();

        $result = [];
        $result['list'] = $model->order('sort,id')->select();

        return success($result);
    }

    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);
        // 验证提交
        $validate = new ConfigDictionaryValidate();
        if (!$validate->scene('create')->check($post)) return error([], $validate->getError());

        $model = new ConfigDictionary();
        try {
            $model->save($post);
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }

        if ($model->id > 0) {
            // 核销表单token
            $formLogic = new FormLogic();
            $formLogic->removeToken($post['form_token']);

            return success([], '添加Picker成功');
        } else {
            return error([], '添加Picker失败');
        }
    }

    public function save()
    {
        $post = $this->request->post();
        $validate = new ConfigDictionaryValidate();
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());

        $model = new ConfigDictionary();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '数据不存在');

        $rs = $row->save($post);
        if ($rs) {
            // 核销表单token
            $formLogic = new FormLogic();
            $formLogic->removeToken($post['form_token']);

            // 清除缓存
            $commonLogic = new CommonPickerLogic();
            $commonLogic->resetCache($post['field']);
            return success([], '编辑Picker信息成功');
        } else {
            return error([], '编辑Picker信息失败');
        }
    }

    public function delete()
    {
        $post = $this->request->post();
        // 验证提交
        $validate = new ConfigDictionaryValidate();
        if (!$validate->scene('delete')->check($post)) return error([], $validate->getError());

        $model = new ConfigDictionary();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '数据不存在');
        $rs = $row->delete();

        if ($rs) {
            return success([], '删除成功');
        } else {
            return error([], '删除失败');
        }
    }
}